/*
 * Copyright (c) 2020 IUV Inc. All rights reserved.
 * 项目名称：IUV TXY
 * 文件名：UserInfoServiceImpl.java
 * Date：20-10-22 下午3:13
 * Author：Will
 */

package com.iuv.imdemo.service.impl;

import com.iuv.imdemo.domain.DemoImUserInfo;
import com.iuv.imdemo.repository.DemoImUserInfoRepository;
import com.iuv.imdemo.service.ImAccountService;
import com.iuv.imdemo.service.UserInfoService;
import com.iuv.imdemo.util.IuvPOIUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * IM例子-用户业务实现类
 */
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {
    private final static Logger logger = LoggerFactory.getLogger(UserInfoServiceImpl.class);
    private static String BASE_PATH=System.getProperty("user.dir");
    @Autowired
    private DemoImUserInfoRepository demoImUserInfoRepository;
    @Autowired
    private ImAccountService imAccountService;

    /**
     * 通过用户ID模糊查询用户列表
     *
     * @param key
     * @return
     */
    @Override
    public List<String> queryAllUserIdMatch(String key) {
        key = StringUtils.trimToEmpty(key);
        List<String> allUserIdList = null;
        List<DemoImUserInfo> demoImUserInfoList = demoImUserInfoRepository.queryTop20ByUserIdLike("%" + key + "%");
        if (demoImUserInfoList != null && demoImUserInfoList.size() > 0) {
            allUserIdList = demoImUserInfoList.stream().map(e -> e.getUserId()).collect(Collectors.toList());
        }
        return allUserIdList;
    }

    /**
     * 通过用户ID查询用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public DemoImUserInfo queryUserInfoByUserId(String userId) {
        return demoImUserInfoRepository.findTopByUserId(userId);
    }

    /**
     * 导入用户到IM服务
     *
     */
    @Override
    public void importUserInfo() {
        logger.info("初始化系统帐号");
        List<DemoImUserInfo> userInfoList=new ArrayList<>();
        try {
            String basePath= ResourceUtils.getURL("classpath:").getPath();
            /**
             * TODO 问题一 初始化user_init.xls文件对象，赋值给 accourtFile
             * 注意文件路径分隔符尽量使用 File.separator
             */
            File accourtFile = new File(basePath+File.separator+"data"+File.separator+"user_init.xls");

            /**
             * END
             */

            // 创建对Excel工作簿文件的引用
            Workbook workbook = new HSSFWorkbook(new FileInputStream(accourtFile));
            Sheet sheet = workbook.getSheetAt(0);

            Row row = null;
            Cell cell = null;
            int rowCount = sheet.getLastRowNum() + 1;
            if (rowCount == 1) {
                logger.info("您上传的文件没有任何用户信息！");
            }
            DemoImUserInfo userInfo = null;
            for (int i = 1; i < rowCount; i++) {
                userInfo = new DemoImUserInfo();
                // 从第二行开始读信息
                row = sheet.getRow(i);
                int cellIndex = 0;
                // 读用户名
                cell = row.getCell(cellIndex++);
                String userId = StringUtils.trimToEmpty(IuvPOIUtil.getStringByCellIgnoreAll(cell));
                if (StringUtils.isBlank(userId) || userId.length() > 25 || !StringUtils.isAlphanumeric(userId)) {
                    continue;
                }
                userInfo.setUserId(userId);
                // 读密码
                /**
                 * TODO 问题二 读取excel表中的密码，存放在 password
                 * 提示：仿照上面读取用户名的代码
                 */
                cell = row.getCell(cellIndex);
                String password = String.format(IuvPOIUtil.getStringByCellIgnoreAll(cell));
                if (StringUtils.isBlank(password) || password.length() > 25 || !StringUtils.isAlphanumeric(password)) {
                    continue;
                }
                /**
                 * END
                 */
                // 密码需要用密文存储
                userInfo.setPassword(DigestUtils.md5Hex(password.getBytes()));

                // basic info
                userInfo.setCreateTime(new Date());
                userInfoList.add(userInfo);
                workbook.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(),e.getCause());
        }
        if (userInfoList!=null&&userInfoList.size()>0) {
            List<String> userIdList=new ArrayList<>();
            for (DemoImUserInfo userInfo : userInfoList) {
                if (queryUserInfoByUserId(userInfo.getUserId()) == null) {
                    demoImUserInfoRepository.save(userInfo);
                    userIdList.add(userInfo.getUserId());
                }
            }

            imAccountService.importAccount(userIdList);
        }
        logger.info("初始化系统帐号结束。。。。。。。。");
    }
}
